<script setup lang="ts">
import { login } from '@/api/users'
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules,FormInstance } from 'element-plus'
import { useTokenStore } from '@/stores/mytoken' 
import { useRouter, useRoute } from 'vue-router'
//表单响应式数据
const store = useTokenStore()
const router = useRouter()
const route = useRoute()
const form = reactive({
  phone: '18201288771',
  password: '111111'
})

const onSubmit = async() => {
  try {
    await formRef.value?.validate()
    // 调用登录接口
    const res = await login(form)
   
    if(!res.data.success) {
      ElMessage.error('登录失败，请检查手机号或密码')
      return
    }
    // 保存token
    store.saveToken(res.data.content)
    await nextTick()
    ElMessage.success('登录成功')
    // 跳转到上次想访问的页面或首页
    let redirect = route.query.redirect || '/'
    if (Array.isArray(redirect)) {
      redirect = redirect[0]
    }
    router.replace(redirect)
  } catch (err) {
    ElMessage.error("表单验证失败")
    // 可以根据需要处理错误
  }
}

const rules = reactive<FormRules>({
  phone:[{
    required: true,
    message:"请输入电话号码",
    //光标离开时验证
    trigger: 'blur',

  },
  {
    // 手机号格式验证
    pattern: /^1\d{10}$/,
    message:"请输入正确的11位手机号",
    trigger: 'blur',
  }
],
  password:[
    {
      required: true,
      message:"请输入密码",
      trigger: 'blur',
    },
    {
      min: 6,
      max: 20,
      message: "密码长度在6-20位之间",
      trigger: 'blur',
    },
  ],
})


const formRef = ref<FormInstance>()
</script>

<template>
    <div class="login">
      <!-- ref="formRef"  不要有多余的空格……………… -->
  <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" label-position="top" size="large">
    <h2>登录</h2>
    <!-- prop=phone  就是这个表单用其中phone 的规则 -->
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="form.phone" />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" />
    </el-form-item>
    
    
    <el-form-item>
      <el-button type="primary" @click="onSubmit" >登陆</el-button>
    
    </el-form-item>
  </el-form>
  </div>
</template>

<style scoped>
.login {
  background-color: #ccc;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(to top,#fbc2eb 0%,#a6c1ee 100%);
  .el-form{
    width: 300px;
    background-color: #fff;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0px 4px 10px gray;

    .el-form-item {
      margin-bottom: 20px;
    }

    .el-button {
      width: 100%;
      margin-top: 30px;
    }
  }
}
</style>
